package dao

import (
	"errors"
	"go-shop-demo/app/common"
	"go-shop-demo/app/consts"
	"go-shop-demo/app/model"
)

func CheckGoods(name string) bool {
	db := common.GetDB()
	var goods model.Goods
	err := db.Where("goods_name = ?", name).First(&goods).Error
	if err != nil {
		return false
	}
	return true
}

func AddGoods(goods model.Goods) error {
	tx := common.GetTx()
	err := tx.Create(&goods).Error // 通过数据的指针来创建
	if err != nil {
		return errors.New("插入商品数据失败")
	}
	tx.Commit()
	return nil
}

func DeleteGoods(id uint) {
	tx := common.GetTx()
	goods := model.Goods{}
	err := tx.Where("id = ?", id).Delete(&goods).Error
	common.CheckErr(err, consts.ServerError, "")
	return
}

func GetGoods(page, size int) (total int64, items []model.Goods) {
	db := common.GetDB()
	db.Model(&model.Goods{}).Count(&total)
	err := db.Model(&model.Goods{}).Limit(size).Offset(page * size).Find(&items).Error
	common.CheckErr(err, consts.ServerError, "")
	return
}

func GetSingleGoods(goodsname string) (goods model.Goods) {
	db := common.GetDB()
	goods = model.Goods{}
	err := db.Where("goods_name = ?", goodsname).First(&goods).Error
	common.CheckErr(err, consts.ServerError, "")
	return goods
}
